package com.crazy.bookstore.controller;

import com.google.code.kaptcha.Producer;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * @author: 卢辉宇
 * @date: 2022/12/29 19:00
 * @description: 验证码类
 */
@Controller
public class KaptchaController {

    @Resource
    private Producer kaptchaProducer;

    @GetMapping("/verify_code")
    public void createVerifyCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
        /*1. 清空响应头的各种数据，及缓存的数据*/
        response.setDateHeader("Expires",0); //响应立即过期
        response.setHeader("Cache-Control","no-store,no-cache,must-revalidate"); //浏览器不做存储和缓存
        response.setHeader("Cache-Control","post-check=0,pre-check=0"); //关闭前置与后置检查
        response.setHeader("Pragma","no-cache"); //关闭缓存
        response.setContentType("image/png"); //设置响应内容类型

        /*2. 生成验证码图片*/
        String text = kaptchaProducer.createText(); //生成图片的内容

        request.getSession().setAttribute("kaptchaVerifyCode",text); //把生成的文本暂存到session中

        BufferedImage image = kaptchaProducer.createImage(text); //正式生成图片验证码

        ServletOutputStream outputStream = response.getOutputStream(); //创建输出流对象

        ImageIO.write(image,"png",outputStream); //通过图片流的方式发给前端

        outputStream.flush();
        outputStream.close();
    }
}
